﻿using Iworld.Backstage.Framework.AdministratorService;
using Iworld.Backstage.Framework.AuthorService;
using System;
using System.Collections.ObjectModel;
using System.Linq;
namespace Iworld.Backstage.Framework
{
    /// <summary>
    /// 用户列表
    /// </summary>
    public class UserListViewModel : ShowListViewModelBase<AuthorExport,AuthorServiceClient>
    {
        public UserListViewModel()
            : base(PageCategory.用户管理.ToString(),Page.用户列表.ToString())
        {
            client.GetUsersCompleted += this.WrapEventHandler<GetUsersCompletedEventArgs>(GetUsersCompleted);
            StatusGroups.Add(new FilterBoxModel("全部", null, Refresh, true));
            StatusGroups.Add(new FilterBoxModel(AuthorStatus.正常.ToString(), AuthorStatus.正常,Refresh));
            StatusGroups.Add(new FilterBoxModel(AuthorStatus.禁止访问.ToString(), AuthorStatus.禁止访问, Refresh));
        }

        string keyword;
        ObservableCollection<FilterBoxModel> statusGroups = new ObservableCollection<FilterBoxModel>();

        public ObservableCollection<FilterBoxModel> StatusGroups
        {
            get { return statusGroups; }
            set
            {
                if (statusGroups == value) { return; }
                statusGroups = value;
                OnPropertyChanged("StatusGroups");
            }
        }

        public string Keyword
        {
            get { return keyword; }
            set
            {
                if (keyword == value) { return; }
                keyword = value == "" ? null : value;
                OnPropertyChanged("Keyword");
                Refresh(1);
            }
        }

     

        void GetUsersCompleted(object sender, GetUsersCompletedEventArgs e)
        {
            if (e.Result.Success)
            {
                this.PageIndex = e.Result.PageIndex;
                this.TotalPage = e.Result.CountOfPage;
                UpdateLsit(e.Result.List);
            }
            else
            {
                ShowError(e.Result.Error);
            }
        }



        protected override void Refresh(object obj)
        {
            int pageIndex = obj == null ? this.PageIndex : Convert.ToInt32(obj);
            AuthorStatus? sta = null;
            FilterBoxModel selected = statusGroups.First(x => x.Selected);
            if (selected!=null)
            {
                if (selected.Value!=null)
                sta = (AuthorStatus?)selected.Value;
            }
            client.GetUsersAsync(new GetUsersImport() {
                PageIndex = pageIndex,Keyword=this.Keyword, Status = sta,
                Token = DataManager.GetValue<AdministratorExport>(DataKey.Administrator_Info).Token
            });
        }

        protected override void Reset(object obj)
        {
            this.PageIndex = 1;
            this.Keyword = null;
            this.StatusGroups.First(x => x.Value == null).Selected = true;
            Refresh(null);
        }
    }
}
